<template>
  <el-dialog
    v-model="visible"
    :title="`设计工序 - ${craftInfo.craftName}`"
    width="95%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    fullscreen
    class="operation-designer-dialog"
  >
    <div class="designer-container">
      <!-- 顶部工艺信息栏 -->
      <div class="craft-info-bar">
        <div class="info-item">
          <span class="label">工艺编号：</span>
          <span class="value">{{ craftInfo.craftCode }}</span>
        </div>
        <div class="info-item">
          <span class="label">工艺名称：</span>
          <span class="value">{{ craftInfo.craftName }}</span>
        </div>
        <div class="info-item">
          <span class="label">工序数量：</span>
          <el-tag type="success">{{ operations.length }} 个</el-tag>
        </div>
        <div class="info-actions">
          <el-button type="primary" @click="addOperation">
            <el-icon><Plus /></el-icon>
            新增工序
          </el-button>
        </div>
      </div>

      <!-- 主内容区：上下分栏 -->
      <div class="content-area">
        <!-- 上部：工序流程图 -->
        <div class="flow-section">
          <div class="section-header">
            <h3>
              <el-icon><Connection /></el-icon>
              工序流程图
            </h3>
          </div>
          <div class="section-content">
            <OperationFlowVisualization
              :operations="operations"
              :key="`designer-visualization-${visualizationKey}`"
              @operation-click="handleOperationClick"
            />
          </div>
        </div>

        <!-- 下部：工序列表 -->
        <div class="table-section">
          <div class="section-header">
            <h3>
              <el-icon><List /></el-icon>
              工序详情列表
            </h3>
          </div>
          <div class="section-content">
            <el-table
              :data="operations"
              :loading="loading"
              style="width: 100%"
              border
              stripe
              :max-height="800"
            >
              <el-table-column
                prop="operationCode"
                label="工序编号"
                width="200"
                fixed="left"
              />
              <el-table-column
                prop="operationName"
                label="工序名称"
                width="300"
                show-overflow-tooltip
              />
              <el-table-column
                prop="operationTotalStdTime"
                label="标准时长(min)"
                width="130"
                align="center"
              >
                <template #default="{ row }">
                  <el-tag size="small" type="success">
                    {{ row.operationTotalStdTime || "-" }}min
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                prop="operationPreparedTime"
                label="准备时长(min)"
                width="140"
                align="center"
              >
                <template #default="{ row }">
                  <span class="time-value">
                    {{ row.operationPreparedTime || "-" }}min
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="operationEquipType"
                label="设备类型"
                width="150"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.operationEquipType || "-" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="operationPersonSkill"
                label="人员技能"
                width="150"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.operationPersonSkill || "-" }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="250" fixed="right">
                <template #default="{ row }">
                  <el-button
                    type="text"
                    size="small"
                    @click="editOperation(row)"
                    class="edit-btn"
                  >
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="deleteOperation(row)"
                    class="delete-btn"
                  >

                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>

    <!-- 工序表单对话框 -->
    <OperationFormDialog
      v-model="operationDialogVisible"
      :operation-data="currentEditOperation"
      :craft-info="craftInfo"
      :all-operations="operations"
      @saved="handleOperationSaved"
    />
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Edit,
  Delete,
  Connection,
  List,
} from "@element-plus/icons-vue";
import OperationFlowVisualization from "./OperationFlowVisualization.vue";
import OperationFormDialog from "./OperationFormDialog.vue";
import { operationApi } from "@/api/operation.js";

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  craftInfo: {
    type: Object,
    required: true,
  },
});

// Emits
const emit = defineEmits(["update:modelValue", "refresh"]);

// 数据
const operations = ref([]);
const loading = ref(false);
const visualizationKey = ref(0);
const operationDialogVisible = ref(false);
const currentEditOperation = ref(null);

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

// 加载工序数据
const loadOperations = async () => {
  if (!props.craftInfo?.id) return;

  loading.value = true;
  try {
    const response = await operationApi.queryOperationByCraftId({
      craftId: props.craftInfo.id,
    });
    operations.value = response.data || [];
    console.log("加载工序数据成功:", operations.value);
  } catch (error) {
    console.error("加载工序数据失败:", error);
    ElMessage.error("加载工序数据失败");
    operations.value = [];
  } finally {
    loading.value = false;
  }
};

// 刷新可视化
const refreshVisualization = () => {
  visualizationKey.value++;
};

// 新增工序
const addOperation = () => {
  currentEditOperation.value = null;
  operationDialogVisible.value = true;
};

// 编辑工序
const editOperation = (operation) => {
  currentEditOperation.value = { ...operation };
  operationDialogVisible.value = true;
};

// 删除工序
const deleteOperation = async (operation) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除工序 "${operation.operationName}" 吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await operationApi.deleteOperation({ id: operation.id });
    ElMessage.success("工序删除成功");

    // 从本地数据中移除
    const index = operations.value.findIndex((op) => op.id === operation.id);
    if (index > -1) {
      operations.value.splice(index, 1);
    }

    refreshVisualization();
    emit("refresh");
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除工序失败:", error);
      ElMessage.error("删除工序失败");
    }
  }
};

// 工序保存后处理
const handleOperationSaved = (savedOperation) => {
  console.log("工序保存成功:", savedOperation);

  // 智能刷新逻辑
  if (savedOperation.id) {
    // 编辑模式：更新本地数据
    const index = operations.value.findIndex(
      (op) => op.id === savedOperation.id
    );
    if (index > -1) {
      operations.value[index] = { ...savedOperation };
    } else {
      // 如果没找到，重新加载
      loadOperations();
    }
  } else {
    // 新增模式：重新加载
    loadOperations();
  }

  refreshVisualization();
  // 注意：不在这里触发 refresh 事件，而是在对话框关闭时统一刷新
};

// 根据ID获取完整工序数据（必要时刷新后再取）
const getOperationDetailById = async (operationId) => {
  if (!operationId) return null;
  // 先在当前内存中查找
  let found = operations.value.find((op) => op.id === operationId);
  if (found) return { ...found };

  // 若未找到，尝试按当前工艺ID刷新后再查找
  if (props.craftInfo?.id) {
    await loadOperations();
    found = operations.value.find((op) => op.id === operationId);
    if (found) return { ...found };
  }
  return null;
};

// 流程图节点点击处理：加载完整数据并打开表单
const handleOperationClick = async (operation) => {
  try {
    console.log("点击工序节点:", operation);
    const fullData = await getOperationDetailById(operation.id);
    console.log("选中节点的完整工序数据:", fullData || operation);
    editOperation(fullData || operation);
  } catch (e) {
    console.error("加载工序详情失败", e);
    editOperation(operation);
  }
};

// 监听对话框打开/关闭
watch(
  () => props.modelValue,
  (newVal, oldVal) => {
    if (newVal && !oldVal) {
      // 对话框打开时，加载数据
      console.log("工序设计器打开，加载工序数据");
      loadOperations();
    } else if (!newVal && oldVal) {
      // 对话框关闭时，触发刷新事件
      console.log("工序设计器关闭，触发刷新");
      emit("refresh");
    }
  }
);

// 暴露方法
defineExpose({
  loadOperations,
});
</script>

<style scoped>
/* ==================== 对话框样式 ==================== */
.operation-designer-dialog {
  display: flex;
  flex-direction: column;
}

.operation-designer-dialog :deep(.el-dialog__body) {
  flex: 1;
  padding: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* ==================== 设计器容器 ==================== */
.designer-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

/* ==================== 工艺信息栏 ==================== */
.craft-info-bar {
  display: flex;
  align-items: center;
  gap: 24px;
  padding: 16px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item .label {
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
}

.info-item .value {
  color: white;
  font-size: 14px;
  font-weight: 600;
}

.info-actions {
  margin-left: auto;
}

.info-actions .el-button {
  background: rgba(255, 255, 255, 0.95);
  border: none;
  color: #667eea;
  font-weight: 500;
}

.info-actions .el-button:hover {
  background: white;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* ==================== 主内容区 ==================== */
.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
  overflow: hidden;
}

/* ==================== 流程图区域 ==================== */
.flow-section {
  flex: 0 0 55%;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.section-header {
  padding: 12px 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #dee2e6;
}

.section-header h3 {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  color: #495057;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-content {
  flex: 1;
  padding: 16px;
  overflow: auto;
}

/* ==================== 表格区域 ==================== */
.table-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.table-section .section-content {
  padding: 0;
}

/* ==================== 表格样式 ==================== */
.time-value {
  color: #606266;
  font-size: 13px;
}

/* 操作按钮样式 - 符合系统主题 */
.edit-btn {
  color: #667eea !important;
  font-weight: 500;
  transition: all 0.3s ease;
}

.edit-btn:hover {
  color: #764ba2 !important;
  transform: translateY(-1px);
}

.delete-btn {
  color: #f56c6c !important;
  font-weight: 500;
  transition: all 0.3s ease;
}

.delete-btn:hover {
  color: #f78989 !important;
  transform: translateY(-1px);
}

/* ==================== 响应式优化 ==================== */
@media (max-width: 1400px) {
  .craft-info-bar {
    flex-wrap: wrap;
  }

  .info-actions {
    width: 100%;
    margin-left: 0;
    margin-top: 8px;
  }
}
</style>
